package com.example.p001_interview02;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 写一个固定容量同步容器，拥有put和get方法，以及getCount方法，能够支持2个生产者线程以及10个消费者线程的阻塞调用
 * @param <T>
 */
public class Container03<T> {

    private final int MAX = 20;
    private LinkedList<T> c = new LinkedList<>();

    private ReentrantLock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    public void put(T t) {

        lock.lock();
        try {

            while (c.size() == MAX) {
                try {
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            c.add(t);

            consumer.signalAll();

        } finally {
            lock.unlock();
        }
    }

    public T get() {

        lock.lock();
        try {

            while (c.size() == 0) {
                try {
                    consumer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            T t = c.removeFirst();

            producer.signalAll();

            return t;

        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        lock.lock();
        try {
            return c.size();

        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Container03 c = new Container03();

        // 10个消费者
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 开始消费");
                for (int j = 0; j < 4; j++) {
                    Object o = c.get();
                    System.out.println(Thread.currentThread().getName() + " 获得：" + o);
                }
            }, "consumer" + i).start();
        }

        // 2个生产者
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 开始生产");
                for (int j = 0; j < 20; j++) {
                    c.put(Thread.currentThread().getName() +  "-" + j);
                }
                System.out.println(Thread.currentThread().getName() + " 结束生产");

            }, "producter" + i).start();
        }

    }

}
